import Vue from 'vue';
import axios from 'axios';
import Qs from 'qs';
import {LoadingPlugin } from 'vux'
Vue.use(LoadingPlugin)
let [isTest, origin] = [null,  window.document.location.origin] ;
if(origin.indexOf("36.7") > -1 ||  origin.indexOf("localhost") > -1){
  isTest = true
}else{
  isTest = false
}
const url = isTest ?  'http://192.168.3.71:8080' : 'http://report.wsloan.com:8888' 

// const url = 'http://192.168.3.71:8080';

let ajax = function (option) {
  let {url, method, headers = null, data, success} = option;
  console.log('url:',url)
  let config = {
    url,
    method,
  };
  if (headers) {
    Object.assign(config, {headers})
  }
  method.toLowerCase() === 'get' ? Object.assign(config, {params: data}) : Object.assign(config, {data});
  if (method.toLowerCase() === 'post') {
    config.data = Qs.stringify(config.data);
  }
  let promise = axios(config);
  if (success && typeof success === 'function') {
    promise.then(res => success(res))
  }
  return promise;
};
window.initAjax = initAjax;

let initAjax = (method) => {
  return ({api, data, isLoading = true}, baseUrl) => {
    let innerUrl;
 
    let headers = localStorage.getItem("token") ? {Authorization: localStorage.getItem("token")} : null;
    if (baseUrl !== undefined) {
      innerUrl = baseUrl.api;
     
      console.log(baseUrl)
    } else {
      innerUrl = url;
    }
    if (isLoading) {
      Vue.$vux.loading.show({
        text: 'Loading'
      })
    }
    return ajax({
      url: innerUrl + api,
      method,
      headers,
      data,
      success: () => {
        Vue.$vux.loading.hide()
      },
    })
  }
};

export default initAjax;